package com.yeqing.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.internal.ChannelUtils;
import io.netty.util.CharsetUtil;

/**
 * 服务器端 IO处理类
 */
@ChannelHandler.Sharable
public class HandlerServerHello extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 处理收到的数据，并反馈消息到客户端
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务器端收到消息:" + byteBuf.toString(CharsetUtil.UTF_8));

        // 写入并发送到远端
        ctx.writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已收到你发送的消息", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 有异常时打印并关闭通道
        cause.printStackTrace();
        ctx.close();
    }
}
